package com.piece.core.web.authority.token;

import com.piece.core.framework.constant.ParamConstants;
import com.piece.core.framework.constant.ExceptionAuthConstants;
import com.piece.core.framework.constant.SecurityConstants;
import com.piece.core.framework.exception.ServerException;
import com.piece.core.framework.util.basic.I18nUtil;
import com.piece.core.framework.util.string.StringUtil;
import com.piece.core.web.util.AuthenticationUtil;
import org.springframework.security.core.Authentication;
import javax.servlet.http.HttpServletRequest;

public class OpenIdAuthenticationGranter extends CompositeAuthorizationGranter {

    public OpenIdAuthenticationGranter() {
        super(SecurityConstants.OPEN_ID);
    }

    @Override
    public Authentication grant(HttpServletRequest request) {
        String clientId = AuthenticationUtil.getInstance(request).extractClientId();
        if (StringUtil.isEmpty(clientId)) {
            throw new ServerException(I18nUtil.message(ExceptionAuthConstants.CLIENT_INVALID));
        }

        String openId = request.getParameter(ParamConstants.OPENID);
        return new OpenIdAuthenticationToken(openId, clientId);
    }
}
